<?php

namespace Biz\model\redPacket;

use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\service\User;

class RedPacketsAccount extends BaseDbModel
{

    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_redpacket';

    const _DATABASE_ = 'biz_red_packet';

    const _TABLE_NAME = 'red_packets_account';

    public static function getUserListAndCount($where)
    {
        $list = self::getUserList($where);
        $total = self::getUserCount($where);
        return compact('list', 'total');
    }
    public static function getUserList($where)
    {
        if (!isset($where['ORDER'])) {
            $where['ORDER'] = [
                'id' => 'DESC'
            ];
        }
        if (empty($where['AND'])) {
            unset($where['AND']);
        }
        $list = self::select("*", $where);
//        var_dump(self::log());
        $uids = empty($list) ? [] : array_column($list, 'uid');
        $whiteList = \Biz\service\redPacket\RedPackets::getUserTag($uids);

        foreach ($list as $key => $v) {
            $userInfo = User::getUserInfo($v['uid']);
            $list[$key]['nick'] = isset($userInfo['nick']) ? $userInfo['nick'] : '';
            $list[$key]['used_amount'] = bcsub($v['packet_amount'], $v['current_amount'], 2);
            $list[$key]['passed_amount'] = '-';
            $list[$key]['is_white'] = isset($whiteList[$v['uid']]) && ($whiteList[$v['uid']] == 'whitelist');
        }
        return $list;
    }
    public static function getUserCount($where)
    {
        if (isset($where['LIMIT'])) {
            unset($where['LIMIT']);
        }
        if (isset($where['ORDER'])) {
            unset($where['ORDER']);
        }
        $rs = self::count('*',$where);
        return $rs;
    }


    public static function getUserPacketAccount($uid)
    {
        return self::get('*', ['uid' => $uid]);
    }

    public static function hasAccount($uid)
    {
        return self::has(['uid' => $uid]);
    }

    public static function addData($data)
    {
        $now = date('Y-m-d H:i:s');
        $data['addtime'] = $now;
        $data['edittime'] = $now;
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return self::id();
    }

    public static function updateData($data, $where)
    {
        $data['edittime'] = date('Y-m-d H:i:s');
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }
        return true;
    }


}

